import threading
from lib import helper, resp
from lib.snowflake import Snowflake
from models.user_novel_role import UserNovelRole


class NovelRoleService:

    local_data = threading.local()
    local_data.test_list = []

    def __init__(self) -> None:
        self.local_data.test_list = []
        pass

    def role_list(self, NovelId, role_name="", page = 1, limit = 10):
        c = UserNovelRole.table().where("NovelId", NovelId)
        if role_name != "":
            c.where("RoleName", "like", f"%{role_name}%")
        c.where("IsValid", 1)
        count = c.count()
        page_index = (page - 1) * limit
        list = c.take(limit).skip(page_index).get()
        
        return resp.ret_obj({"List": list, "Count": count})

    def role_save(self, role_id=0, data: dict = {}):
        t = UserNovelRole.table()
        info = t.where("RoleId", role_id).first()
        if info:
            rs = t.update(helper.update_data_time(data))
        else:
            data["RoleId"] = Snowflake.unique_id()
            rs = UserNovelRole.table().insert(helper.add_data_time(data))
        if not rs:
            return resp.ret_failed()
        return resp.ret_obj()

    def role_delete(self, role_id):
        rs = UserNovelRole.table().where("RoleId", role_id).update({"IsValid": 0})
        if rs:
            return resp.ret_obj()
        return resp.ret_failed()
